package epam.com.study.xml.classes;

import org.apache.log4j.Logger;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import epam.com.study.xml.enums.StringToEnum;

public class LoadStonesSAX extends DefaultHandler {

	private static final Logger log = Logger.getLogger(LoadStonesSAX.class);
	
	private ListOfStones list = new ListOfStones();
	private Stone stone;
	private VisualParameters visp;
	private String thisElement = "";
	private String thisElement2 = "";
	private String thisElement3 = "";

	public ListOfStones getResult() {
		return list;
	}

	@Override
	public void startDocument() throws SAXException {
		log.info("Start parse XML...");
	}

	@Override
	public void startElement(String namespaceURI, String localName,
			String qName, Attributes atts) throws SAXException {
		thisElement = qName;

		log.info(thisElement);
		switch (thisElement) {
		case "tns:stone":
			thisElement2 = thisElement;
			stone = new Stone();
			break;
		case "tns:visual-parameters":
			thisElement3 = thisElement;
			visp = new VisualParameters();
			break;
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName) {
		if (thisElement2 == "tns:stone") {
			list.addStone(stone);
			thisElement2 = "";
		}
		if (thisElement3 == "tns:visual-parameters") {
			stone.setVisualParameters(visp);
			thisElement3 = "";
		}
		thisElement = "";
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		String value = new String(ch, start, length).trim();
		if (thisElement != null) {
			switch (thisElement) {
			case "tns:id":
				stone.setId(Integer.valueOf(value));
				break;
			case "tns:name":
				stone.setName(value);
				break;
			case "tns:value":
				stone.setValue(Integer.valueOf(value));
				break;
			case "tns:preciousness":
				stone.setPreciousness(StringToEnum.toTypeStone(value));
				break;
			case "tns:origin":
				stone.setOrigin(value);
				break;	
			case "tns:color":
				visp.setColor(StringToEnum.toColor(value));
				break;
			case "tns:transparency":
				visp.setTransparency(Integer.valueOf(value));
				break;
			case "tns:edge":
				visp.setEdge(Integer.valueOf(value));
				break;
			}
		}
	}

	@Override
	public void endDocument() {
		log.info("End parse XML...");
	}
}
